import sys
import os
import sqlite3
from datetime import datetime

# 添加项目根目录到Python路径
backend_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, backend_path)

from database import database

def get_email_logs():
    """
    获取邮件日志（无分页）
    
    Returns:
        list: 日志数据列表
    """
    try:
        conn = database.get_db_connection()
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()
        
        # 执行查询语句，获取system_logs表中的所有记录（按时间倒序）
        cursor.execute("SELECT * FROM system_logs ORDER BY created_at DESC")
        logs = cursor.fetchall()
        
        conn.close()
        
        # 转换为字典列表
        result = [dict(log) for log in logs]
        
        return result
    except Exception as e:
        print(f"获取邮件日志时出错: {str(e)}")
        return []

def add_email_log(message: str, level: str = "INFO"):
    """
    添加邮件日志
    
    Args:
        message: 日志消息
        level: 日志级别（INFO, WARNING, ERROR等）
    
    Returns:
        dict: 操作结果
    """
    try:
        conn = database.get_db_connection()
        cursor = conn.cursor()
        
        # 插入日志记录
        cursor.execute(
            "INSERT INTO system_logs (message, level, created_at) VALUES (?, ?, ?)",
            (message, level, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        )
        
        conn.commit()
        conn.close()
        
        return {"status": "success", "message": "日志添加成功"}
    except Exception as e:
        print(f"添加邮件日志时出错: {str(e)}")
        return {"status": "error", "message": str(e)}

def clear_email_logs():
    """
    清空邮件日志
    
    Returns:
        dict: 操作结果
    """
    try:
        conn = database.get_db_connection()
        cursor = conn.cursor()
        
        # 删除所有日志记录
        cursor.execute("DELETE FROM system_logs")
        
        conn.commit()
        conn.close()
        
        return {"status": "success", "message": "日志清空成功"}
    except Exception as e:
        print(f"清空邮件日志时出错: {str(e)}")
        return {"status": "error", "message": str(e)}